﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using EnetaMvc.ApplicationServices;
using EnetaMvc.ApplicationServices.Dto;
using EnetaMvc.Web.Attributes;
using EnetaMvc.Web.Models;

namespace EnetaMvc.Web.Controllers
{
    public class TagsController : BaseController
    {
        private readonly IContentService _contentService;

        public TagsController(IContentService contentService)
        {
            _contentService = contentService;
        }

        [EnetaAuthorize(Roles = "Administrator")]
        public ActionResult Index()
        {
            TagModel model = BuildDefaultTagModel();

            return View(model);
        }

        [EnetaAuthorize(Roles = "Administrator")]
        [HttpPost]
        public ActionResult Create(TagDto tag, int selectedTagGroupId)
        {
            if (!ModelState.IsValid)
            {
                TagModel model = BuildDefaultTagModel();
                model.Tag = tag;
                return View(model);
            }

            tag.GroupId = selectedTagGroupId.ToString();
            _contentService.SaveTag(tag);
            return RedirectToAction("Index");
        }

        [EnetaAuthorize(Roles = "Administrator")]
        [HttpPost]
        public ActionResult Edit(TagDto tag)
        {
            if (!ModelState.IsValid)
            {
                TagModel model = BuildDefaultTagModel();
                model.Tag = tag;
                return View(model);
            }

            _contentService.SaveTag(tag);
            return RedirectToAction("Index");
        }

        [EnetaAuthorize(Roles = "Administrator")]
        [HttpPost]
        public ActionResult Delete(int id)
        {
            _contentService.DeleteTag(id);
            return RedirectToAction("Index");
        }

        [EnetaAuthorize(Roles = "Administrator")]
        public JsonResult IsTagUsed(int id)
        {
            return Json(_contentService.IsTagUsed(id), JsonRequestBehavior.AllowGet);
        }


        //Private methods

        private TagModel BuildDefaultTagModel()
        {
            TagModel model = new TagModel();
            model.Tags = _contentService.ListTags();
            model.TagGroups = (from p in _contentService.ListTagGroups()
                               select new SelectListItem()
                               {
                                   Text = p.Name,
                                   Value = p.Id.ToString()
                               }).ToList();
            if (model.TagGroups.Count > 0)
                model.SelectedTagGroupId = Convert.ToInt32(model.TagGroups.FirstOrDefault().Value);
            model.Tag = new TagDto();
            
            return model;
        }
    }
}
